<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export'" type="danger" size="small" @click="doExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="doAdd">新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop:'workNumber'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" alt=""> -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="scope">
              {{ formmateType(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column
            label="入职时间"
            prop="timeOfEntry"
            sortable
          />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="doAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes,prev, pager, next"
            :total="total"
            :current-page="page"
            :page-sizes="[3, 5, 10, 20]"
            :page-size="size"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 弹窗 -->
    <el-dialog :visible.sync="showDialog" title="新增员工">
      <empDialog @close="doCancle" @success="doSuccess" />
    </el-dialog>
    <!-- 分配角色弹窗 -->
    <el-dialog :visible.sync="showDialogRole" title="分配角色">
      <AssignRole v-if="showDialogRole" :assign-role-id="curId" @close="doCloseRole" @success="doSuc" />
    </el-dialog>
  </div>
</template>

<script>
import { getEmployee, getDelEmployee } from '@/api/employee'
import empDialog from '@/views/employees/empDialog.vue'
import employeeENUM from '@/constant/employees'
import AssignRole from './assignRole.vue'
const EMPLOYEETYPE = employeeENUM.hireType.reduce((acc, cur) => { acc[cur.id] = cur.value; return acc }, {})
// const obj = {}
// const enm = employeeENUM.hireType.forEach(item =>{ obj[item.id] = item.value})
// console.log(enm)
export default {
  components: { empDialog, AssignRole },
  data() {
    return {
      curId: '',
      list: [],
      total: 0,
      page: 1,
      size: 10,
      // 显示新增|编辑弹窗
      showDialog: false,
      // 显示分配角色弹窗
      showDialogRole: false
    }
  },
  created() {
    // 加载员工信息
    this.loadEmployee()
  },
  methods: {
    async loadEmployee() {
      const { data: res } = await getEmployee({ page: this.page, size: this.size })
      // console.log('员工信息', res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 聘用状态的格式化
    formmateType(typeId) {
      // const item = employeeENUM.hireType.find(item => item.id === typeId)
      // if (item) {
      //   return item.value
      // } else {
      //   return '未知'
      // }
      return EMPLOYEETYPE[typeId] || '未知'
    },
    handleCurrentChange(curpage) {
      console.log(`点击了第几页${curpage}`)
      // 1.更新页码
      this.page = curpage
      // 2.重发请求
      this.loadEmployee()
    },
    handleSizeChange(curSize) {
      // 1.更新每页几条数据
      this.size = curSize
      // 统一跳转第一页
      this.page = 1
      // 2.重发请求
      this.loadEmployee()
    },
    // 删除
    delEmployee(id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        console.log('id是....', id)
        const { data: res } = await getDelEmployee(id)
        console.log('删除员工', res)

        // 如果删除是最后一条数据，则页码要-1
        if (this.list.length === 1) {
          let page = this.page
          page--
          // 页码不能减是0
          // if (this.pageParams.page === 0) {
          //   this.pageParams.page = 1
          // }
          page = Math.max(1, page)
          this.page = page
        }
        this.$message.success('删除成功')
        // 更新页面
        this.loadEmployee()
      }).catch(() => {
      })
    },
    // 新增员工
    doAdd() {
      this.showDialog = true
    },
    // 取消
    doCancle() {
      this.showDialog = false
    },
    // 添加成功
    doSuccess() {
      // 关闭弹窗
      this.showDialog = false
      // 刷新页码
      this.total++
      this.page = Math.ceil(this.total / this.size)
      // 重发请求
      this.loadEmployee()
    },
    // 转换格式
    transformData(rows) {
      const header = Object.keys(rows[0])
      const data = rows.map(item => {
        return header.map(key => {
          return item[key]
        })
      })
      // todo: (1)表头要是中文的 (2) 聘用形式 不要是1，而是'正式'
      return { header, data }
    },
    // 导出excel
    doExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        // excel表示导入的模块对象
        const { data: res } = await getEmployee({ page: this.page, size: this.size })
        // 转换格式
        const { header, data } = this.transformData(res.data.rows)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工工资表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 分配角色
    doAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
    },
    doCloseRole() {
      this.showDialogRole = false
    },
    // 成功,子传父
    doSuc() {
      this.showDialogRole = false
    }
  }

}
</script>

<style>

</style>
